package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.core.graphics.drawable.IconCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewpager.widget.ViewPager;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.tabs.TabLayout;
import com.stark.shortcut.ShortcutHelper;

import java.util.ArrayList;
import java.util.List;

import flc.ast.AppConfig;
import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelAppAdapter;
import flc.ast.bean.MyAppBean;
import flc.ast.databinding.ActivityIconReplaceBinding;
import flc.ast.dialog.IconSelDialog;
import flc.ast.dialog.ShortcutCreateDialog;
import flc.ast.fragment.IconSelTabFragment;
import flc.ast.fragment.TabFragment;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.constant.Extra;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.view.container.StkRecycleView;

public class IconReplaceActivity extends BaseAc<ActivityIconReplaceBinding> {

    public static MyAppBean sAppBean;
    public static int type;
    private Dialog myAddTipDialog,mySelAppDialog;
    private IconSelDialog myIconSelDialog;
    public static final int ENTER_CHOOSE_PHOTO_CODE = 200;
    public static final int ENTER_ICON_CODE = 210;
    public static String sSelIcon;
    private String mIconSrc;
    private SelAppAdapter selAppAdapter;


    @Override
    protected int onCreate() {
        return R.layout.activity_icon_replace;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivIconReplaceBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivAppIcon.setOnClickListener(this);
        mDataBinding.ivReplaceIcon.setOnClickListener(this);
        mDataBinding.ivApplyIcon.setOnClickListener(this);
        //图标选择弹框
        addTipDialog();
        //图标库弹框
//        iconSelDialog();
        //app选择弹框
        selAppDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivReplaceIcon://添加新图标
                myAddTipDialog.show();
                break;
            case R.id.ivDialogAddTipSel://相册选择
                AlbumChooseActivity.type=0;
                startActivityForResult(new Intent(mContext, AlbumChooseActivity.class), ENTER_CHOOSE_PHOTO_CODE);
                myAddTipDialog.dismiss();
                break;
            case R.id.ivDialogAddTipIcon://图标库
                iconSelDialog();
                myAddTipDialog.dismiss();
                break;
            case R.id.ivDialogAddTipCancel://取消
                myAddTipDialog.dismiss();
                break;
            case R.id.ivAppIcon://app
                mySelAppDialog.show();
                break;
            case R.id.ivDialogSelAppCancel:
                mySelAppDialog.dismiss();
                break;
            case R.id.ivApplyIcon://应用图标
                if (sAppBean==null){
                    ToastUtils.showShort(getString(R.string.please_sel_app));
                    return;
                }
                if (TextUtils.isEmpty(mIconSrc)) {
                    ToastUtils.showShort(getString(R.string.please_sel_icon));
                    return;
                }
                String name = mDataBinding.etAppName.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getString(R.string.please_input_name));
                    return;
                }
                if (!ShortcutManagerCompat.isRequestPinShortcutSupported(mContext)) {
                    ToastUtils.showShort(R.string.no_support_hint);
                    return;
                }
                showCreateDialog(ImageUtils.view2Bitmap(mDataBinding.ivReplaceIcon), mDataBinding.etAppName.getText().toString());
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter==selAppAdapter){
            sAppBean=selAppAdapter.getItem(position);
            mDataBinding.ivAppIcon.setImageDrawable(AppUtils.getAppIcon(sAppBean.getName()));
            mDataBinding.tvAppName.setText(AppUtils.getAppName(sAppBean.getName()));
            mySelAppDialog.dismiss();
        }
    }

    @Override
    protected void initData() {
        if (type==0){
            sSelIcon = "";
            mDataBinding.ivAppIcon.setImageDrawable(AppUtils.getAppIcon(sAppBean.getName()));
            mDataBinding.tvAppName.setText(AppUtils.getAppName(sAppBean.getName()));
            mDataBinding.etAppName.setText(AppUtils.getAppName(sAppBean.getName()));
        }else if (type==1){
            sAppBean=null;
            mIconSrc=sSelIcon;
            Glide.with(mContext).load(mIconSrc).into(mDataBinding.ivReplaceIcon);
            mDataBinding.tvAppName.setText(getString(R.string.add_apply));
            mDataBinding.etAppName.setHint(getString(R.string.input_app_name));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

    private ShortcutCreateDialog mDialog;


    private void showCreateDialog(Bitmap sBitmap, String name) {
        mDialog = new ShortcutCreateDialog(this);
        mDialog.mBitmap = sBitmap;
        mDialog.mName = name;
        mDialog.show();
        mDialog.setListener(new ShortcutCreateDialog.Ilistener() {
            @Override
            public void clickConfirm() {
                IconCompat iconCompat;
                iconCompat = IconCompat.createWithBitmap(ImageUtils.view2Bitmap(mDataBinding.ivReplaceIcon));
                boolean isSuc=ShortcutHelper.installShortCut(mDataBinding.etAppName.getText().toString(), iconCompat, sAppBean.getName());
                if (isSuc){
                    ToastUtils.showShort(getString(R.string.set_suc));
                }
            }
        });
    }

    //图标选择弹框
    private void addTipDialog() {
        myAddTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_tip, null);
        myAddTipDialog.setContentView(inflate);
        myAddTipDialog.setCancelable(true);
        Window dialogWindow = myAddTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogAddTipCancel);
        ImageView selImg = inflate.findViewById(R.id.ivDialogAddTipSel);
        ImageView icon = inflate.findViewById(R.id.ivDialogAddTipIcon);
        cancel.setOnClickListener(this);
        selImg.setOnClickListener(this);
        icon.setOnClickListener(this);
    }

    //app选择弹框
    private void selAppDialog() {
        mySelAppDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_app, null);
        mySelAppDialog.setContentView(inflate);
        mySelAppDialog.setCancelable(true);
        Window dialogWindow = mySelAppDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogSelAppCancel);
        StkRecycleView recycleView=inflate.findViewById(R.id.rvAppList);
        cancel.setOnClickListener(this);
        recycleView.setLayoutManager(new GridLayoutManager(mContext,4));
        selAppAdapter=new SelAppAdapter();
        recycleView.setAdapter(selAppAdapter);
        selAppAdapter.setOnItemClickListener(this);
        getAllAppData();
    }


    //图标库弹框
    private void iconSelDialog() {
        myIconSelDialog = new IconSelDialog();
        myIconSelDialog.show(getSupportFragmentManager(), "icon");
        myIconSelDialog.setCancelable(true);
        myIconSelDialog.setIlistener(new IconSelDialog.Ilistener() {
            @Override
            public void clickCancel() {
                myIconSelDialog.dismiss();
            }

            @Override
            public void clickConfirm() {
                if (TextUtils.isEmpty(sSelIcon)) {
                    ToastUtils.showShort(getString(R.string.please_sel_icon));
                    return;
                }
                mIconSrc = sSelIcon;
                Glide.with(mContext).load(mIconSrc).into(mDataBinding.ivReplaceIcon);
                myIconSelDialog.dismiss();
            }
        });
    }

    private void getAllAppData() {
        List<MyAppBean> mMyAppBeanList=new ArrayList<>();
        RxUtil.create(new RxUtil.Callback<List<PackageInfo>>() {
            @Override
            public void doBackground(ObservableEmitter<List<PackageInfo>> emitter) {
                List<PackageInfo> installedPackageInfoList = mContext.getPackageManager()
                        .getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);
                emitter.onNext(installedPackageInfoList);
            }

            @Override
            public void accept(List<PackageInfo> infoList) {
                if (infoList != null && infoList.size() != 0) {
                    for (PackageInfo packageInfo : infoList) {
                        mMyAppBeanList.add(new MyAppBean(packageInfo.packageName, packageInfo.applicationInfo.sourceDir, false));
                    }
                    selAppAdapter.setList(mMyAppBeanList);
                }
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == ENTER_CHOOSE_PHOTO_CODE) {
                mIconSrc = data.getStringExtra(Extra.PATH);
                mDataBinding.ivReplaceIcon.setImageResource(0);
                Glide.with(this).load(mIconSrc).into(mDataBinding.ivReplaceIcon);
            } else if (requestCode == ENTER_ICON_CODE) {
                mIconSrc = data.getStringExtra(Extra.DATA);
                mDataBinding.ivReplaceIcon.setImageResource(0);
                Glide.with(this).load(mIconSrc).into(mDataBinding.ivReplaceIcon);
            }
        }
    }

}